%{
AUTHOR: Felipe Arteaga

DATE:  2020--
-------------------------------------------------------------------------
PROJECT:
-------------------------------------------------------------------------
DESCRIPTION:


El periodo de analisis es desde que se manda el SMSImagen con mineduc
(07-Sep-2020 19:40:48, UTC) y se cierra el proceso el 09-Sep-2020 03:00:00
 O sea una ventana de 1 dia y 7 horas (end of process).

=========================================================================
%}

clc;clear;close all;fclose('all');
feature('DefaultCharacterSet', 'UTF-8');

pcName=char(java.lang.System.getProperty('user.name'));
if(strcmp(pcName,'felipe'))
    % PC Felipe
    myDir='/Users/felipe/Dropbox/';
    projectDir=[myDir,'git/warnings/'];
    projectDirData=[myDir,'projects/warnings/'];
end

addpath(genpath([myDir,'/myMatlabFunctions/']));

dirPlots=[projectDir,'/paper/figuresCL/RDs/'];
dirTable=[projectDir,'/paper/tablesCL/'];

dirData=[projectDirData,'/data/chile/'];




saveFigFile=false;

%% Load data:
anho=2020;
anhoStr=sprintf('%i',anho);

load([dirData,anhoStr,'/inputRD'],'dataRD','feeCats1','simceCats','carosCat','gratisCat','buenosCat','malosCat','descRadios','oferta','distanciasG')

dic=struct;
dic.('treatedImageSMSImage')='Opened image link';
dic.('treatedSMSImage')='Received SMS';
dic.('intendedSMSImage')='Assigned to SMS';
dic.('riskSMSImage')='Predicted placement risk';
dic.('schoolsAddedPreSIEnd')='Schools added (31 hrs window)';

%% RD

restrToAll=dataRD.riskSMSImage>0.02&dataRD.pobSMSImagen==1&dataRD.grade<2&(dataRD.pobWhatsapp==0|dataRD.controlWhatsapp==1);
subpobs=cell(4,3);
subpobs(1,:)={'All',            restrToAll,'all'};
subpobs(2,:)={'w/image simple',   restrToAll&(dataRD.typeImageSMSImage==1|dataRD.riskSMSImage<=.3),'wImage1'};
subpobs(3,:)={'w/image bar',      restrToAll&(dataRD.typeImageSMSImage==2|dataRD.riskSMSImage<=.3),'wImage2'};
subpobs(4,:)={'w/image seats',    restrToAll&(dataRD.typeImageSMSImage==3|dataRD.riskSMSImage<=.3),'wImage3'};
%subpobs(5,:)={'Control WhatsApp**',restrToAll&dataRD.controlWhatsapp==1,'controlW'};



data=dataRD(:,{'treatedSMSImage','riskSMSImage','schoolsAddedPreSIEnd','treatedImageSMSImage'});
inAnyPob=false(height(data),1);

% Generate stata commands
commands=cell(size(subpobs,1)*4,2);
counter=1;

regressions={'First stage (SMS received)','fs_SMS';'First stage (Open Link to image)','fs_image';'ITT','itt';'IV*','iv'};
for p=1:size(subpobs,1)
    
    data.(sprintf('subpop%i',p))=subpobs{p,2};
    inAnyPob=inAnyPob|subpobs{p,2};
    
    commands(counter,:)={sprintf('fs_SMS_%i',p),sprintf('rdrobust treatedSMSImage riskSMSImage if subpop%i==1, c(.3)  p(2) h(.28 .68)',p)};counter=counter+1;

    commands(counter,:)={sprintf('fs_image_%i',p),sprintf('rdrobust treatedImageSMSImage riskSMSImage if subpop%i==1, c(.3)  p(2) h(.28 .68)',p)};counter=counter+1;

    commands(counter,:)={sprintf('itt_%i',p),sprintf('rdrobust schoolsAddedPreSIEnd riskSMSImage if subpop%i==1, c(.3)  p(2) h(.28 .68)',p)};counter=counter+1;

    commands(counter,:)={sprintf('iv_%i',p),sprintf('rdrobust schoolsAddedPreSIEnd riskSMSImage if subpop%i==1, c(.3)  p(2) h(.28 .68) fuzzy(treatedSMSImage)',p)};counter=counter+1;
    
    
end


data=data(inAnyPob,:);
res=stataCommand(commands,data);

%%
head=subpobs(:,1)';

cantPobs=(size(subpobs,1));
cantRegs=(size(regressions,1));

matrix_nl=nan(cantRegs,cantPobs);
matrix_nr=nan(cantRegs,cantPobs);
matrix_b=nan(cantRegs,cantPobs);
matrix_sd=nan(cantRegs,cantPobs);
matrix_pOrder=nan(cantRegs,cantPobs);
cell_pl=cell(cantRegs,cantPobs);
cell_pr=cell(cantRegs,cantPobs);

for p=1:cantPobs
    for r=1:cantRegs
        
        res_i=res.(sprintf('%s_%i',regressions{r,2},p));
        
        % Beta
        matrix_b(r,p)=res_i.tau_cl;
        % Sd Beta
        matrix_sd(r,p)=res_i.se_tau_cl;
        
        % N
        matrix_nl(r,p)=res_i.N_h_l;
        matrix_nr(r,p)=res_i.N_h_r;
        
        
        if(not(strcmp(regressions{r,2},'iv')))
        figure
        a=plotRD(res_i,dataRD,subpobs{p,2});
        
       
        
        easyExport([dirPlots,sprintf('%s_SMSImage_%s_%s.png',anhoStr,regressions{r,2},subpobs{p,3})]);
        end
        
    end
    
end

%%

matTable=[matrix_b;matrix_nl(end,:);matrix_nr(end,:)];
matTable_sd=[matrix_sd;nan(2,size(matrix_sd,2))];

opt=struct;
opt.note={'*Treated status is defined as "SMS received", what is different than "read". Some of them also opened the link to the image.',...
    };
opt.header=head;
opt.stderrs=mat2cellstr(matTable_sd,'conParentesis',true,'precisionDecimal','%.3f');
opt.primeracolumna=[regressions(:,1);{'NL';'NR'}];
%opt.stars=getStars(matTable,matTable_sd);
opt.addColumnNumber=true;
opt.columnafantasma=[1 4];
opt.filafantasma=[4];
opt.title='(SMS with link to image) Outcome: schools added in 2 days window';
opt.panel={0,'A. RD'};
opt.alignmentFirstCol={'L{3cm}'};
opt.adjust=true;
opt.file=sprintf('%s%i_tableSMSImage',dirTable,anho);
tabla=cell2latex(mat2cellstr(matTable,'precisionDecimal','%.3f','revisarFilas',true),'opts',opt);
compileLatex(tabla)

